package com.lagou.edu.utils;

import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionUtils {

    private ConnectionUtils() {

    }

    // 饿汉式的单例
    private static ConnectionUtils connectionUtils = new ConnectionUtils();

    public static ConnectionUtils getInstance() {
        return connectionUtils;
    }

    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();



    public Connection getCurrentThreadConnection() throws SQLException {

        // 判断当前线程中是否已经绑定了连接
        Connection connection = threadLocal.get();
        if(connection == null) {
            // 从连接池拿连接并绑定到当前线程
            connection = DruidUtils.getInstance().getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }

}
